//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package org_evaluate_api_serv

import (
	"context"
	"time"

	"atomgit.com/openlinksaas-org/api-server/dao"
	"atomgit.com/openlinksaas-org/api-server/dao/org_dao"
	"atomgit.com/openlinksaas-org/api-server/dao/org_eval_dao"
	"atomgit.com/openlinksaas-org/proto-gen-go.git/org_evaluate_api"
	"github.com/google/uuid"
	"go.mongodb.org/mongo-driver/mongo"
)

func (apiImpl *OrgEvaluateApiImpl) AddTarget(ctx context.Context, req *org_evaluate_api.AddTargetRequest) (*org_evaluate_api.AddTargetResponse, error) {
	sessionItem, ok := dao.CacheDao.GetSession(ctx, req.SessionId)
	if !ok {
		return &org_evaluate_api.AddTargetResponse{
			Code:   org_evaluate_api.AddTargetResponse_CODE_WRONG_SESSION,
			ErrMsg: "会话不存在",
		}, nil
	}
	orgItem, err := org_dao.OrgInfoDao.Get(ctx, req.OrgId)
	if err != nil {
		return &org_evaluate_api.AddTargetResponse{
			Code:   org_evaluate_api.AddTargetResponse_CODE_NO_ORG,
			ErrMsg: "组织不存在",
		}, nil
	}
	selfMemberItem, err := org_dao.MemberDao.Get(ctx, req.OrgId, sessionItem.UserId)
	if err != nil {
		return &org_evaluate_api.AddTargetResponse{
			Code:   org_evaluate_api.AddTargetResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	}

	if !(orgItem.OwnerUserId == sessionItem.UserId || selfMemberItem.MemberPermInfo.ManageEvaluateTarget) {
		return &org_evaluate_api.AddTargetResponse{
			Code:   org_evaluate_api.AddTargetResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	}

	nowTime := time.Now().UnixNano() / 1e6
	targetId := uuid.NewString()

	dbSess, err := dao.StartSession()
	if err != nil {
		return nil, err
	}
	defer dao.EndSession(dbSess)

	ret, err := dbSess.WithTransaction(ctx, func(sessCtx mongo.SessionContext) (interface{}, error) {
		err = org_eval_dao.TargetDao.Insert(sessCtx, &org_eval_dao.EvaluateTargetInfoDbItem{
			TargetId:      targetId,
			OrgId:         req.OrgId,
			TargetName:    req.TargetName,
			EvaluateCount: 0,
			TimeStamp:     nowTime,
		})
		if err != nil {
			return nil, err
		}
		return &org_evaluate_api.AddTargetResponse{
			Code:     org_evaluate_api.AddTargetResponse_CODE_OK,
			TargetId: targetId,
		}, nil
	})
	if err != nil {
		return nil, err
	}
	return ret.(*org_evaluate_api.AddTargetResponse), nil
}

func (apiImpl *OrgEvaluateApiImpl) ListTarget(ctx context.Context, req *org_evaluate_api.ListTargetRequest) (*org_evaluate_api.ListTargetResponse, error) {
	emptyList := []*org_evaluate_api.EvaluateTargetInfo{}

	sessionItem, ok := dao.CacheDao.GetSession(ctx, req.SessionId)
	if !ok {
		return &org_evaluate_api.ListTargetResponse{
			Code:       org_evaluate_api.ListTargetResponse_CODE_WRONG_SESSION,
			ErrMsg:     "会话不存在",
			TargetList: emptyList,
		}, nil
	}
	exist, err := org_dao.OrgInfoDao.Exist(ctx, req.OrgId)
	if err != nil {
		return nil, err
	}
	if !exist {
		return &org_evaluate_api.ListTargetResponse{
			Code:       org_evaluate_api.ListTargetResponse_CODE_NO_ORG,
			ErrMsg:     "组织不存在",
			TargetList: emptyList,
		}, nil
	}
	exist, err = org_dao.MemberDao.Exist(ctx, req.OrgId, sessionItem.UserId)
	if err != nil {
		return nil, err
	}
	if !exist {
		return &org_evaluate_api.ListTargetResponse{
			Code:       org_evaluate_api.ListTargetResponse_CODE_NO_PERMISSION,
			ErrMsg:     "没有权限",
			TargetList: emptyList,
		}, nil
	}

	targetItemList, err := org_eval_dao.TargetDao.List(ctx, req.OrgId)
	if err != nil {
		return nil, err
	}

	targetList := []*org_evaluate_api.EvaluateTargetInfo{}
	for _, targetItem := range targetItemList {
		targetList = append(targetList, targetItem.ToEvaluateTargetInfo())
	}

	return &org_evaluate_api.ListTargetResponse{
		Code:       org_evaluate_api.ListTargetResponse_CODE_OK,
		TargetList: targetList,
	}, nil
}

func (apiImpl *OrgEvaluateApiImpl) UpdateTarget(ctx context.Context, req *org_evaluate_api.UpdateTargetRequest) (*org_evaluate_api.UpdateTargetResponse, error) {
	sessionItem, ok := dao.CacheDao.GetSession(ctx, req.SessionId)
	if !ok {
		return &org_evaluate_api.UpdateTargetResponse{
			Code:   org_evaluate_api.UpdateTargetResponse_CODE_WRONG_SESSION,
			ErrMsg: "会话不存在",
		}, nil
	}
	orgItem, err := org_dao.OrgInfoDao.Get(ctx, req.OrgId)
	if err != nil {
		return &org_evaluate_api.UpdateTargetResponse{
			Code:   org_evaluate_api.UpdateTargetResponse_CODE_NO_ORG,
			ErrMsg: "组织不存在",
		}, nil
	}
	selfMemberItem, err := org_dao.MemberDao.Get(ctx, req.OrgId, sessionItem.UserId)
	if err != nil {
		return &org_evaluate_api.UpdateTargetResponse{
			Code:   org_evaluate_api.UpdateTargetResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	}

	if !(orgItem.OwnerUserId == sessionItem.UserId || selfMemberItem.MemberPermInfo.ManageEvaluateTarget) {
		return &org_evaluate_api.UpdateTargetResponse{
			Code:   org_evaluate_api.UpdateTargetResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	}

	exist, err := org_eval_dao.TargetDao.Exist(ctx, req.OrgId, req.TargetId)
	if err != nil {
		return nil, err
	}
	if !exist {
		return &org_evaluate_api.UpdateTargetResponse{
			Code:   org_evaluate_api.UpdateTargetResponse_CODE_NO_TARGET,
			ErrMsg: "评估指标不存在",
		}, nil
	}

	dbSess, err := dao.StartSession()
	if err != nil {
		return nil, err
	}
	defer dao.EndSession(dbSess)

	ret, err := dbSess.WithTransaction(ctx, func(sessCtx mongo.SessionContext) (interface{}, error) {
		err = org_eval_dao.TargetDao.UpdateName(sessCtx, req.OrgId, req.TargetId, req.TargetName)
		if err != nil {
			return nil, err
		}
		return &org_evaluate_api.UpdateTargetResponse{
			Code: org_evaluate_api.UpdateTargetResponse_CODE_OK,
		}, nil
	})
	if err != nil {
		return nil, err
	}
	return ret.(*org_evaluate_api.UpdateTargetResponse), nil
}

func (apiImpl *OrgEvaluateApiImpl) RemoveTarget(ctx context.Context, req *org_evaluate_api.RemoveTargetRequest) (*org_evaluate_api.RemoveTargetResponse, error) {
	sessionItem, ok := dao.CacheDao.GetSession(ctx, req.SessionId)
	if !ok {
		return &org_evaluate_api.RemoveTargetResponse{
			Code:   org_evaluate_api.RemoveTargetResponse_CODE_WRONG_SESSION,
			ErrMsg: "会话不存在",
		}, nil
	}
	orgItem, err := org_dao.OrgInfoDao.Get(ctx, req.OrgId)
	if err != nil {
		return &org_evaluate_api.RemoveTargetResponse{
			Code:   org_evaluate_api.RemoveTargetResponse_CODE_NO_ORG,
			ErrMsg: "组织不存在",
		}, nil
	}
	selfMemberItem, err := org_dao.MemberDao.Get(ctx, req.OrgId, sessionItem.UserId)
	if err != nil {
		return &org_evaluate_api.RemoveTargetResponse{
			Code:   org_evaluate_api.RemoveTargetResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	}

	if !(orgItem.OwnerUserId == sessionItem.UserId || selfMemberItem.MemberPermInfo.ManageEvaluateTarget) {
		return &org_evaluate_api.RemoveTargetResponse{
			Code:   org_evaluate_api.RemoveTargetResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	}
	targetItem, err := org_eval_dao.TargetDao.Get(ctx, req.OrgId, req.TargetId)
	if err != nil { //记录不存在
		return &org_evaluate_api.RemoveTargetResponse{
			Code: org_evaluate_api.RemoveTargetResponse_CODE_OK,
		}, nil
	}
	if targetItem.EvaluateCount > 0 {
		return &org_evaluate_api.RemoveTargetResponse{
			Code:   org_evaluate_api.RemoveTargetResponse_CODE_HAS_EVALUATE,
			ErrMsg: "存在关联评估",
		}, nil
	}

	dbSess, err := dao.StartSession()
	if err != nil {
		return nil, err
	}
	defer dao.EndSession(dbSess)

	ret, err := dbSess.WithTransaction(ctx, func(sessCtx mongo.SessionContext) (interface{}, error) {
		err = org_eval_dao.TargetDao.Remove(sessCtx, req.OrgId, req.TargetId)
		if err != nil {
			return nil, err
		}
		return &org_evaluate_api.RemoveTargetResponse{
			Code: org_evaluate_api.RemoveTargetResponse_CODE_OK,
		}, nil
	})
	if err != nil {
		return nil, err
	}
	return ret.(*org_evaluate_api.RemoveTargetResponse), nil
}
